import time

import pygame

from actor.xiao_tie import XiaoTie
from game import SCREEN_HEIGHT, SCREEN_WIDTH, GAME_TITLE, ScenePassStatus, DEFAULT_POS_X, DEFAULT_POS_Y
from scene.fail_scene import FailScene
from scene.final_scene import FinalScene
from scene.welcome_scene import WelcomeScene
from scene.win_scene import WinScene
from scene.tunnel_war_scene import TunnelWarScene

"""
游戏启动类（负责整体的循环运行与场景切换）
"""


class TunnelWarGame:
    def __init__(self):
        # 初始化pygame
        pygame.init()
        pygame.mixer.init()
        # 获取游戏时钟
        self.clock = pygame.time.Clock()
        # 创建游戏的窗口 1280 * 720 根据要显示图片的大小设置
        self.surface = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
        pygame.display.set_caption(GAME_TITLE)
        self.xiao_tie = XiaoTie(DEFAULT_POS_X, DEFAULT_POS_Y)
        self.current_scene = FinalScene(self.xiao_tie)

    def run(self):
        while True:
            # 游戏循环
            down_flag = False
            for event in pygame.event.get():
                # 关闭事件，进行退出处理
                if event.type == pygame.QUIT:
                    exit()
                elif event.type == pygame.KEYDOWN:
                    down_flag = True
            key_list = pygame.key.get_pressed()
            # 1,获取场景的视窗图像
            current_surface = self.current_scene.get_current_surface()
            # 2,绘制窗口
            self.surface.blit(current_surface, (0, 0))
            # 3,场景的运动
            self.current_scene.run(down_flag, key_list)
            self.clock.tick(20)
            pass_status, next_scene_name = self.current_scene.get_pass_status()
            if pass_status != ScenePassStatus.normal:
                if next_scene_name:
                    next_scene = globals()[next_scene_name](self.xiao_tie)
                    print(next_scene)
                    time.sleep(0.5)
                    self.current_scene = next_scene
                else:
                    break

            # 调用flip方法更新显示,也可以使用update方法
            pygame.display.flip()
